<template>
  <div class="kxz-kfgl">
    <section class="kxz-kfgl-top" v-if="0">
      <header>
        <span class="bsType">业务类型：</span>
        <el-radio-group v-model="selType">
          <template v-if="power === 1">
            <el-radio label="业务组" :class="$style.topCheckbox">业务组</el-radio>
            <el-radio label="答疑组" :class="$style.topCheckbox">答疑组</el-radio>
            <el-radio label="回访组" :class="$style.topCheckbox">回访组</el-radio>
          </template>
          <el-radio v-else :label="selType" :class="$style.topCheckbox">{{selType}}</el-radio>
        </el-radio-group>
      </header>
      <div class="ordersWrapper">
        <table class="hdTable">
          <tr>
            <th></th>
            <th v-text="selType"></th>
          </tr>
        </table>
        <table class="bdTable">
          <tr v-for="(oArr, oIndex) in cuOrderListByPage" :key="oIndex">
            <td v-for="(item, index) in oArr" :key="index" v-text="item">
            </td>
          </tr>
        </table>
        <el-pagination @current-change="handleCurrentChange" layout="prev, pager, next" :page-size="orderPageSize" :total="orderList[0].slice(1).length">
        </el-pagination>
        <div class="emptyTip" v-if="cuOrderListByPage.empty">
          <span>暂无记录</span>
        </div>
      </div>
    </section>
    <section class="kxz-kfgl-bottom">
      <header>
        <span class="left" style="float:left">
          <el-button :class="orderByMonth == 'current'?'active' : ''" @click="handleOBM('current')">本月排班
          </el-button>
          <el-button :class="orderByMonth == 'next'?'active' : ''" @click="handleOBM('next')">下月排班
          </el-button>
        </span>
        <div class='div2'>
              <el-upload
                class="upload-demo dadai-upload"
                action="https://jsonplaceholder.typicode.com/posts/"
                ref="uploadAvatar"
                accept="*"
                :multiple="false"
                :auto-upload="false">
                <el-button size="small" type="primary">导入excel</el-button>
            </el-upload>
            <el-button size="small" type="primary"  class='sub' @click="submitUpload"  :disabled ="clickState">点击上传</el-button>
          </div>
        <span class="right">
          <el-button
            v-for="(item,index) in cuGroups"
            :key="index"
            :class="orderByGroup === item? 'active' :(orderByGroup === '客服主管'&&index===0?'active':'')"
            @click="handleOBG(item)"
            v-text="item"
          >
          </el-button>
        </span>

      </header>
      <table class="orderDateTable">
        <tr>
          <th v-for="(tTitle, tIndex) in ['日','一','二','三','四','五','六']" :key="tIndex" v-text="tTitle" :style="{width: `${1 / 7 * 100}%`}"></th>
        </tr>
        <tr v-for="(rowData, rIndex) in cuOrderDateList" :key="rIndex">
          <td v-for="(dateMsg, dIndex) in rowData" :key="dIndex">
            <div v-if="dateMsg" class="showOrder" @click="handleEditOrder(dateMsg.data.Date)">
              <p class="date">{{dateMsg.date}}</p>
              <template v-if="dateMsg.data && (dateMsg.data.MorNum > 0 || dateMsg.data.NigNum > 0 || dateMsg.data.ZhongNum >0)">
                <p v-if="dateMsg.data.MorNum">
                  <span class="orderType mor">早班</span>{{gCNByGid(dateMsg.data.UserGroupId)}} {{dateMsg.data.MorNum > 2 ? `等${dateMsg.data.MorNum}` : dateMsg.data.MorNum}}人
                </p>
                <p v-if="dateMsg.data.NigNum">
                  <span class="orderType nig">晚班</span>{{gCNByGid(dateMsg.data.UserGroupId)}} {{dateMsg.data.NigNum > 2 ? `等${dateMsg.data.NigNum}` : dateMsg.data.NigNum}}人
                </p>
                <p v-if="dateMsg.data.ZhongNum">
                  <span class="orderType nig">活动班</span>{{gCNByGid(dateMsg.data.UserGroupId)}} {{dateMsg.data.ZhongNum > 2 ? `等${dateMsg.data.ZhongNum}` : dateMsg.data.ZhongNum}}人
                </p>
                <!-- <p>
                  <span class="orderType nig">值班</span>{{gCNByGid(dateMsg.data.UserGroupId)}} {{dateMsg.data.NigNum > 2 ? `等${dateMsg.data.NigNum}` : dateMsg.data.NigNum}}人
                </p> -->
              </template>
            </div>
          </td>
        </tr>
      </table>
    </section>
    <el-dialog :visible.sync="dialogForm" :modal="false">
      <el-form label-position="top" label-width="80px" :model="form">
        <el-form-item label="早班人员">
          <el-select v-model="form.selMorList" multiple placeholder="请选择">
            <el-option v-for="item in form.kfAll" :key="item.id" :label="item.UserName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="晚班人员">
          <el-select v-model="form.selNigList" multiple placeholder="请选择">
            <el-option v-for="item in form.kfAll" :key="item.id" :label="item.UserName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动班人员">
          <el-select v-model="form.selZhoList" multiple placeholder="请选择">
            <el-option v-for="item in form.kfAll" :key="item.id" :label="item.UserName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="值班人员">
          <el-select v-model="form.selNigList" multiple placeholder="请选择">
            <el-option v-for="item in form.kfAll" :key="item.id" :label="item.UserName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item class="confirmOrder" v-if="this.dateState">
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'orders-manage',
  data() {
    const orderByMonth = 'current'
    const orderList = this._initOrderList()
    const orderDateList = this._initOrderDateList(orderByMonth)
    const {power, userGroup} = this.$store.getters.getUserInfo
    const selType = userGroup === '超级管理员' ? '业务组' : userGroup
    return {
      power,
      clickState:false,
      selType,
      dateState:true,
      dialogForm: false,
      orderCurrentPage: 1,
      orderPageSize: 6,
      orderList,
      orderByMonth,
      orderByGroup: selType,
      orderDateList,
      curDate: '',
      form: {
        kfAll: null,
        selMorList: [],
        selNigList: [],
        selZhoList:[]
      }
    }
  },
  computed: {
    cuOrderListByPage() {
      const orderList = this.orderList
      const pageIndex = this.orderCurrentPage
      const pageSize = this.orderPageSize
      const ret = []
      if (orderList.empty) {
        return orderList
      }
      orderList.map((oa, oi) => {
        const title = this._oIndex2Title(oi)
        ret[oi] = [title, ...oa.slice((pageIndex - 1) * pageSize + 1, pageIndex * pageSize + 1)]
      })
      ret.empty = false
      return ret
    },
    cuOrderDateList() {
      const odList = this.orderDateList
      const mType = this.orderByMonth
      // 如果返回的数据正常
      if (odList.length > 5) {
        //
        const tmpa = [[], [], [], [], [],[]]  // 日历最长有6行,然后如果最后一行没有数据则删除
        const selFDAY = new Date(odList[0].Date)
        const fDay = selFDAY.getDay() // 获取选定月第一天的星期
        odList.map((dOrder, dIndex) => {
          const dObj = new Date(dOrder.Date)
          const date = dObj.getDate()
          const selDay = dObj.getDay()
          let dSum = date + fDay
          /**
           * 判断的标准是根据元素的个数，满7个说明够一行
           */
          let i = dSum % 7 === 0 ? Number.parseInt(dSum / 7, 10) - 1  : Number.parseInt(dSum / 7, 10)
          tmpa[i][selDay] = {
            date,
            data: dOrder
          }
        })
        if(tmpa[tmpa.length -1].length === 0){
          tmpa.slice(tmpa.length -1 , 1)
        }
        return tmpa
      }
      return mType ? this._initOrderDateList(mType) : odList
    },
    cuGroups(){
      const power = this.power
      const orderByGroup = this.orderByGroup
      
      if(power === 1){
        return ['业务组','答疑组','回访组']
      }else if(power === 2 || power === 5) {
        return [orderByGroup]
      }
    },
  },
  watch: {
    selType(gType) {
      this.getOrdersByGroup()
      return
    }
  },
  mounted() {
   
    // 获取排班汇总数据
    this.getOrdersByGroup()

    // 获取当月排班数据
    this.getOrderByMAG()

    // 获取所有客服的数据
    this.getKFallByGroup()
  },
  methods: {
    async submitUpload() {
        this.clickState = true
        try{
          const formData = new FormData()
          const files = this.$refs.uploadAvatar.uploadFiles
          // 添加提交参数
          if(files.length > 0){
            formData.append('userfile', files[0]['raw'])
          }
          const url = window.path + 'order//uploadLb.do'
          const res = await fetch(url,{
            method:'post',
            mode:'cors',
            body:formData
          })
          const data = await res.json()
          if(data.state === 0 && data.content){
            this.$message({
              type:'success',
              message:'提交成功'
           })
            this.clickState = false
            this.$refs.uploadAvatar.clearFiles();
            return
          }
          this.$toast({message:data.message})
          this.$message({
            type: 'error',
            message:data.message,
          })
        this.clickState = false
        }catch(e){
          console.warn('接口kfgl/uploadQn.do:',e.message)
          this.$warn('接口kfgl/uploadQn.do执行出错')
        }
        
        
    },
    handleCurrentChange(currentPage) {
      this.orderCurrentPage = currentPage
    },
    handleOBM(mType) {
      if (mType === this.orderByMonth) {
        return
      }
      this.orderByMonth = mType
      this.getOrderByMAG()
    },
    handleOBG(gType) {
      if (gType === this.orderByGroup) {
        return
      }
      this.orderByGroup = gType
      
      this.getOrderByMAG()
      this.getKFallByGroup()
    },
    handleEditOrder(date) {
      const orderByMonth = this.orderByMonth
      const nowDate = new Date().getDate()
      const selDate = new Date(date).getDate()
      
      if(orderByMonth === 'current' && nowDate > selDate){
        this.dateState = false
      }else{
        this.dateState = true
      }
      this.form.selMorList = []
      this.form.selNigList = []
      this.form.selZhoList = []
      this.curDate = date
      this.getOrderInDay()
      this.dialogForm = true
    },
    handleSubmit() {
      // const morList = this.form.selMorList
      const nigList = this.form.selNigList
      // if (morList.length === 0) {
      //   this.$message({
      //     message: '白班不能为空(⊙o⊙)哦',
      //     type: 'warning'
      //   });
      //   return
      // }
      // if (nigList.length === 0) {
      //   this.$message({
      //     message: '晚班不能为空(⊙o⊙)哦',
      //     type: 'warning'
      //   });
      //   return
      //}
      this.getInsertSubmit()
      // if (this._isUniq(morList, nigList)) {
      //   this.getInsertSubmit()
      // } else {
      //   this.$message({
      //     message: '白晚班重复啦 小心yo (*^__^*) 嘻嘻……',
      //     type: 'warning'
      //   });
      // }
    },
    _datesByYM(y, m) {
      const dates = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
      if (m === 1) {
        return y % 100 !== 0 ? (y % 4 === 0 ? (dates[m] + 1) : dates[m])
          : (y % 400 === 0 ? (dates[m] + 1) : dates[m])
      }
      return dates[m]
    },
    _oIndex2Title(i) {
      switch (i) {
        case 0:
          return '名字'
        case 1:
          return '本月出勤天数'
        case 2:
          return '本月晚班天数'
        case 3:
          return '本月已出勤晚班'
        case 4:
          return '下月已安排出勤'
        default:
          return '下月已安排晚班'
      }
    },
    _gType2gId(gType) {
      const groupModel = this.$store.getters.getGroup
      
      const gArr = Object.entries(groupModel)
      let ret
      if(gType!=='业务组'&&gType!=='答疑组'&&gType!=='回访组'){
        gType='业务组'
      }
      gArr.forEach((item) => {
        if(item[1] === gType){
          ret = item[0]
        }
      })
      return ret
    },
    _gStr2gCN(gType){
      switch(gType){
        case 'yw':
          return '业务组'
        case 'hf':
          return '回访组'
        default:
          return '答疑组'
      }
    },
    _initOrderList() {
      const orderList = []
      orderList.empty = true
      for (let i = 0, l = 6; i < l; i++) {
        let title = this._oIndex2Title(i)
        orderList[i] = [title, '无']
      }
      return orderList
    },
    _initOrderDateList(mType) {
      const dObj = new Date()
      let y = dObj.getFullYear()
      let m = dObj.getMonth()
      if (mType === 'current') {
        m = m + 1
      } else {
        y = m === 11 ? y + 1 : y
        m = m === 11 ? 1 : (m + 2)
      }
      const selFDAY = new Date(y + '-' + m + '-1')   // 选定月份的第一天日期
      const fDay = selFDAY.getDay() // 获取选定月第一天的星期
      const maxDates = this._datesByYM(selFDAY.getFullYear(), selFDAY.getMonth())
      const tmpa = [[], [], [], [], []]
      for (let i = 0, tl = tmpa.length; i < tl; i++) {
          const suba = tmpa[i]
          for (let j = 0, sl = 7; j < sl; j++) {
            if ((i === 0 && j > (fDay - 1)) || i > 0) {
              const date = (j + 1) + 7 * i - fDay
              if (date < (maxDates + 1)) {
                tmpa[i][j] = {
                  date
                }
              } else {
                tmpa[i][j] = null
              }
            }
          }
        }
        return tmpa
    },
    _getIdsByArr(arr) {
      const tmpa = []
      arr.map((item, index) => {
        tmpa.push(item.kfid)
      })
      return tmpa
    },
    _isUniq(arr1, arr2) {
      if ((arr1.length === 0 && arr2.length > 0) || (arr1.length > 0 && arr2.length === 0)) {
        return true
      }
      if (arr1.length > 0 && arr2.length > 0) {
        let sign = true
        arr1.map((item, index) => {
          if (arr2.findIndex(v => v === item) > -1) {
            sign = false
          }
        })
        return sign
      }
    },
    gCNByGid(gId){
      const gModel = this.$store.getters.getGroup
      return gModel[gId]
    },
    async getOrdersByGroup() {
      let api
      try{
        const gType = this.selType
        switch (gType) {
          case '业务组':
            api = 'order/loadYWZOrderAll.do'
            break
          case '答疑组':
            api = 'order/loadDYZOrderAll.do'
            break
          default:
            api = 'order/loadHFZOrderAll.do'
            break
        }
        const {data} = await this.$get(this,{
          api
        })
        const selOrders = data['content']['orderGroup']
        const orderList = this._initOrderList()
        if (data.state === 1 || selOrders.length === 0) {
          return
        }
        selOrders.map((order, oIndex) => {
          orderList.map((aItem, aIndex) => {
            let prop;
            switch (aIndex) {
              case 0:
                prop = 'kfName'
                break
              case 1:
                prop = 'workDays'
                break
              case 2:
                prop = 'workNightDays'
                break
              case 3:
                prop = 'workedNightDays'
                break
              case 4:
                prop = 'nextWorkDays'
                break
              default:
                prop = 'nextWorkedNightDays'
                break
            }
            if (oIndex === 0) {
              orderList[aIndex].pop()
            }
            orderList[aIndex].push(order[prop])
          })
        })
        orderList.empty = false
        this.orderList = orderList
        
      }catch(e){
        this.$warn(`系统${api}接口报错`)
      }
    },
    async getOrderByMAG() {
      let api
      try{
        const mType = this.orderByMonth
        const gType = this.orderByGroup
        const params = {
          UserGroupId: this._gType2gId(gType)
        }
        switch (mType) {
          case 'current':
            api = 'order/selectNumInMonth.do'
            break
          default:
            api = 'order/selectNumNextMonth.do'
            break
        }
        
        const {data} = await this.$get(this,{
          api,
          data: params
        })
        // 模拟数据
        
        if (data.state === 0) {
          this.orderDateList = data.content
        }
      }catch(e){
        this.$warn(`系统${api}接口报错`)
      }
    },
    async getKFallByGroup() {
      
      try{
        const params = {
          UserGroupId: this._gType2gId(this.orderByGroup),
        }
        
        const {data} = await this.$get(this,{
          api: 'order/selectKFByGroupId.do',
          data: params
        })
     
        if (data.state === 0) {
          
          this.form.kfAll = data.content
        }
      }catch(e){
        this.$warn('系统order/selectKFByGroupId.do接口报错')
      }
    },
    async getOrderInDay() {
      try{
        const params = {
          UserGroupId: this._gType2gId(this.orderByGroup),
          Date: this.curDate
        }
        const {data} = await this.$get(this, {
          api: 'order/selectPeoplesInDay.do',
          data: params
        })
        if (data.state === 0) {
          this.form.selMorList = this._getIdsByArr(data.content.MorPeoples)
          this.form.selNigList = this._getIdsByArr(data.content.NigPeoples)
          this.form.selZhoList = this._getIdsByArr(data.content.zhoPeoples)
        }
      }catch(e){
        // this.$warn('系统order/selectPeoplesInDay.do接口报错')
      }
    },
    async getInsertOrder(data){
      return this.$get(this,{
        api: 'order/insertOrder.do',
        data
      })
    },
    async getInsertSubmit() {
      try{
        const morList = this.form.selMorList
        const nigList = this.form.selNigList
        const zhoList = this.form.selZhoList
        const getInsertOrder = this.getInsertOrder
        // 8.22 找后台理清批量插入的逻辑？
        const Date = this.curDate
        const dataMor = {
          kfID: morList.join(','),
          Date,
          type: '早班',
          UserGroupId: this._gType2gId(this.orderByGroup),
        }
        const dataZho = {
          kfID: zhoList.join(','),
          Date,
          type: '活动班',
          UserGroupId: this._gType2gId(this.orderByGroup),
        }
        const dataNig = {
          kfID: nigList.join(','),
          Date,
          type: '晚班',
          UserGroupId: this._gType2gId(this.orderByGroup),
        }
        // const resArr = await Promise.all([
        //   getInsertOrder(dataMor),
        //   getInsertOrder(dataNig),
        //   getInsertOrder(dataZho)
        // ]).then((item1)=>{
        //   console.log(item1)
        // })
        let newobj = {
          dataMor,
          dataZho,
          dataNig
        }
        const {data} = await getInsertOrder(newobj)

        // 目的：为了达到都插入数据的目的，如果其中有一种情况数据没有插入都要报错警告
        // const sign = resArr.every(v => {
        //   return v.data.state === 0
        // })
        // const sign = data.state
        
        if (data.state == 0 && data.content) {
          this.$message({
            message: '排班完成',
            type: 'success'
          })
          this.getOrderByMAG()
          this.dialogForm = false
        } else {
          this.$message({
            message: '服务器刚才上厕所去了 再排一次班吧',
            type: 'warning'
          })
        }
      }catch(e){
        //this.$warn('系统order/insertOrder.do接口报错')
      }
    }
  }
}
</script>

<style lang="scss" module>
.topCheckbox {
  $tpListColor: #7b8897;
  color: $tpListColor;
  font-size: 18px !important;
}
</style>

<style lang="scss">
$tableBorderColor:#dddfe6;
$tableBgColor:#fff;
.kxz-kfgl {
  table {
    width: 100%;
    border-collapse: separate !important;
    border-top: 1px solid $tableBorderColor;
    border-left: 1px solid $tableBorderColor;
    th,
    td {
      border-right: 1px solid $tableBorderColor;
      border-bottom: 1px solid $tableBorderColor;
      background: $tableBgColor;
      text-align: center;
    }
    th {
      height: 69px;
      line-height: 69px;
    }
  }
  .el-dialog__wrapper {
    top: 80px;
    .el-dialog {
      width: 480px;
      top: 50% !important;
      transform: translate(-50%, -50%);
      border-radius: 8px;
    }
    .el-dialog {
      box-shadow: 0 1px 30px rgba(0, 0, 0, .3);
    }
    .el-dialog__body {
      padding: 30px 80px 40px;
    }
    .el-form-item__label {
      width: 100%;
      padding-bottom: 16px;
      font-size: 16px;
      color: #444;
      text-align: center;
    }
    .el-select {
      width: 100%;
    }
    .el-input input {
      background-color: #fafbfc;
    }
    .confirmOrder {
      text-align: center;
      .el-button {
        padding: 11px 59px;
      }
    }
  }
}

.div2{
  margin-left:30px;
  width:300px;
  display: inline-block;
}
.div2 .upload-demo{
  float:left;
  width:175px;
}
.div2 .upload-demo .el-upload-list__item-name{
  font-size:12px;
}
.div2 .sub{
  float:left;
  margin-left:15px;
}
.kxz-kfgl-top {
  $bstpColor: #444;
  $tpListColor: #7b8897;
  $titleTableColor: $bstpColor;
  $listTableThColor: $bstpColor;
  $listTableTdColor: $tpListColor;
  header {
    overflow: hidden;
    padding-bottom: 20px;
  }
  .bsType {
    float: left;
    font-size: 18px;
    color: $bstpColor;
    font-weight: 600;
    margin-right: 9px;
  }
  .ordersWrapper {
    position: relative;
    th {
      &:first-child {
        width: 200px;
      }
    }
    td {
      height: 60px;
      line-height: 60px;
      font-size: 14px;
      &:first-child {
        width: 200px;
      }
    }
    .bdTable {
      border-top: none;
      table-layout: fixed;
    }
    .emptyTip {
      $color: $bstpColor;
      position: absolute;
      top: 71px;
      right: 1px;
      bottom: 33px;
      left: 202px;
      z-index: 6;
      background-color: #fff;
      color: $color;
      font-size: 22px;
      font-weight: 600;
      span {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }
    .el-pagination {
      text-align: right;
    }
  }
}

.kxz-kfgl-bottom {
  $btmBorderColor: #dddfe6;
  $btnDftBgColor: #ecf0f3;
  $btnDftColor: #bac2cb;
  $btnChgBgColor: #5394fc;
  $btnChgColor: #fff;

  margin-top: 20px;
  header {
    padding: 20px 23px;
    border: 1px solid $btmBorderColor;
    border-bottom: none;
    background: $tableBgColor;
    .right {
      float: right;
    }
    .el-button {
      padding: 11px 29px;
      color: $btnDftColor;
      background: $btnDftBgColor;
      border: none;
      transition:all .3s;
      &:hover {
        color: $btnChgColor;
        background: $btnChgBgColor;
      }
      &.active {
        color: $btnChgColor;
        background: $btnChgBgColor;
      }
    }
  }
 
  .orderDateTable {
    td {
      position: relative;
      height: 130px;
    }
    .showOrder {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      
      padding-left: 20px;
      font-size: 14px;
      color: #8893a0;
      p {
        margin-bottom: 8px;
        text-align: left;
      }
      .date {
        margin-bottom: 12px;
        text-align: left;
      }
      .orderType {
        padding: 4px 7px;
        border-radius: 4px;
        color: #fff;
        margin-right: 6px;
        &.mor {
          background: #5394fc;
        }
        &.zhong {
          background: #ccc;
        }
        &.nig {
          background: #ffa838;
        }
      }
    }
  }
}
</style>


